// pages/auto/getuserinfo.js
const app = getApp();
import config from '../../utils/config.js'
var Base64 = require("../../utils/base64.js");
var CID = config.CID;
var version = config.version;
var logo = config.logo;
var WEBSITENAME = config.getWebsiteName;
var Api = require('../../utils/api.js');
var wxApi = require('../../utils/wxApi.js')
var wxRequest = require('../../utils/wxRequest.js');
Page({

  /**
   * 页面的初始数据
   */
  data: {
    logo: logo,
    WEBSITENAME: WEBSITENAME,

  },

  /**
   * 生命周期函数--监听页面加载
   */
  onLoad: function (options) {

  },

  /**
   * 生命周期函数--监听页面初次渲染完成
   */
  onReady: function () {

  },

  /**
   * 生命周期函数--监听页面显示
   */
  onShow: function () {

  },

  /**
   * 生命周期函数--监听页面隐藏
   */
  onHide: function () {

  },

  /**
   * 生命周期函数--监听页面卸载
   */
  onUnload: function () {

  },

  /**
   * 页面相关事件处理函数--监听用户下拉动作
   */
  onPullDownRefresh: function () {

  },

  /**
   * 页面上拉触底事件的处理函数
   */
  onReachBottom: function () {

  },

  /**
   * 用户点击右上角分享
   */
  onShareAppMessage: function () {

  },
  getuserinfo: function (res) {
    var self = this;
    var wxLogin = wxApi.wxLogin();
    var jscode = '';
    wxLogin().then(response => {
      jscode = response.code
    }).
      //获取用户信息
      then(response => {
        console.log(res.detail.userInfo);
        console.log("成功获取用户信息(公开信息)");
        app.globalData.userInfo = res.detail.userInfo;
        app.globalData.isGetUserInfo = true;
        wx.setStorageSync('userInfo', res.detail.userInfo);
        wx.setStorageSync('isGetUserInfo', true);
        var url = Api.getOpenidUrl();
        var data = {
          js_code: jscode,
          encryptedData: res.detail.encryptedData,
          iv: res.detail.iv,
          avatarUrl: res.detail.userInfo.avatarUrl
        }
        var postOpenidRequest = wxRequest.postRequest(url, data);
        //获取openid
        postOpenidRequest.then(response => {
          
          if (response.data.status == '200') {
            //console.log(response.data.openid)
            console.log("openid 获取成功");
            app.globalData.openid = response.data.openid;
            app.globalData.isGetOpenid = true;
            wx.setStorageSync('openid', response.data.openid);
            wx.setStorageSync('isGetOpenid', true);

            wx.navigateBack({
              delta: 1,
            })


          }
          else {
            console.log(response.data.message);
          }
        })
      })
      .catch(function (error) {
        console.log('error: ' + error.errMsg);
      })
  },
})